package com.chenyue.cm.live.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.live.dao.JdLiveMapper;
import com.chenyue.cm.live.domain.JdLive;
import com.chenyue.cm.live.service.JdLiveService;
import com.chenyue.cm.live.vo.LiveUser;
import com.chenyue.cm.live.vo.MixStreamParam;
import com.chenyue.cm.live.vo.SetLiveUser;
import com.chenyue.cm.tecentCloud.LiveConfig;
import com.chenyue.cm.user.dao.JdAppUserMapper;
import com.chenyue.cm.user.dao.JdAppUserRoleMapper;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdAppUserRole;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.live.v20180801.LiveClient;
import com.tencentcloudapi.live.v20180801.models.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author chenyue-cm
 */
@Service(value = "JdLiveService")
public class JdLiveServiceImpl extends BaseServiceImpl<JdLive> implements JdLiveService {

    private final JdLiveMapper jdLiveMapper;

    private final JdAppUserMapper jdAppUserMapper;

    private final JdAppUserRoleMapper jdAppUserRoleMapper;

    public JdLiveServiceImpl(
            @Qualifier("jdLiveMapper") JdLiveMapper jdLiveMapper,
            @Qualifier("jdAppUserMapper") JdAppUserMapper jdAppUserMapper,
            @Qualifier("jdAppUserRoleMapper") JdAppUserRoleMapper jdAppUserRoleMapper) {
        this.jdLiveMapper = jdLiveMapper;
        this.jdAppUserMapper = jdAppUserMapper;
        this.jdAppUserRoleMapper = jdAppUserRoleMapper;
    }

    @Override
    @Resource(name = "jdLiveMapper")
    public void setBaseMapper(LcBaseMapper<JdLive, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    @Override
    public Page<List<LiveUser>> getLiveUserList(String userId, Integer page, Integer rows, Pageable pageInfo) {
        List<LiveUser> returnList = new ArrayList<>();
        LambdaQueryWrapper<JdLive> wrapper = new QueryWrapper<JdLive>().lambda();
        wrapper.eq(JdLive::getType, 2);
        if (userId != null) {
            wrapper.eq(JdLive::getParentUser, userId);
        }
        if (pageInfo != null) {
            Map<String, Object> pageSearch = pageInfo.getPageSearch();
            if (pageSearch != null) {
                if (null != pageSearch.get("SEARCH_LIKE_live_name")) {
                    wrapper.like(JdLive::getLiveName, String.valueOf(pageSearch.get("SEARCH_LIKE_live_name")));
                }
            }
        }
        Integer total = jdLiveMapper.selectCount(wrapper);
        Page<List<LiveUser>> result = new Page<>(page, rows, total);
        //拼接分页语句
        wrapper.last(result.convertPage());
        List<JdLive> list = jdLiveMapper.selectList(wrapper);
        for (JdLive jdLive : list) {
            LiveUser liveUser = new LiveUser();
            liveUser.setLiveId(jdLive.getId());
            liveUser.setLiveName(jdLive.getLiveName());
            liveUser.setLiveNum(jdLive.getLiveNum());
            liveUser.setRole(jdLive.getRole() == 1 ? "裁判/解说员" : "赛场助理");
            liveUser.setRoleId(jdLive.getRole());
            liveUser.setIntroduce(jdLive.getIntroduce());
            liveUser.setPushUrl(jdLive.getPushUrl());
            liveUser.setPushExpire(jdLive.getPushExpire());
            liveUser.setType(jdLive.getType());
            JdAppUser appUser = jdAppUserMapper.selectById(jdLive.getUserId());
            liveUser.setLiveUser(appUser.getUserName());
            liveUser.setHeadImg(appUser.getHeadImg());
            liveUser.setPhone(appUser.getMobile());
            returnList.add(liveUser);
        }
        result.setContent(returnList);
        return result;
    }

    @Override
    public List<LiveUser> getJdLiveUserList(String userId) {
        List<LiveUser> returnList = new ArrayList<>();
        LambdaQueryWrapper<JdLive> wrapper = new QueryWrapper<JdLive>().lambda();
        wrapper.eq(JdLive::getType, 2);
        if (userId != null) {
            wrapper.eq(JdLive::getParentUser, userId);
        }
        List<JdLive> jdLives = jdLiveMapper.selectList(wrapper);
        for (JdLive jdLive : jdLives) {
            LiveUser liveUser = new LiveUser();
            liveUser.setLiveId(jdLive.getId());
            liveUser.setLiveName(jdLive.getLiveName());
            liveUser.setLiveNum(jdLive.getLiveNum());
            liveUser.setRole(jdLive.getRole() == 1 ? "裁判/解说员" : "赛场助理");
            liveUser.setIntroduce(jdLive.getIntroduce());
            liveUser.setPushUrl(jdLive.getPushUrl());
            liveUser.setPushExpire(jdLive.getPushExpire());
            liveUser.setType(jdLive.getType());
            JdAppUser appUser = jdAppUserMapper.selectById(jdLive.getUserId());
            liveUser.setLiveUser(appUser.getUserName());
            liveUser.setHeadImg(appUser.getHeadImg());
            liveUser.setPhone(appUser.getMobile());
            returnList.add(liveUser);
        }
        return returnList;
    }

    @Override
    public Success<String> setLiveUser(List<SetLiveUser> liveUserList, Integer userId) {
        for (SetLiveUser liveUser : liveUserList) {
            JdAppUser user = getUserByIdOrPhone(liveUser.getNumber());
            final JdLive one = lambdaQuery().eq(JdLive::getUserId, user.getId()).last(" limit 1 ").one();
            if (one != null) {
                continue;
            }
            //输入的是手机号的话，能找到 就设置主播 ，找不到 创建新用户并设置主播
            //输入的是编号的话，能找到 就新增 ，找不到 不创建新用户
            user.setParentId(userId);
            jdAppUserMapper.updateById(user);
            JdLive live = new JdLive();
            live.setUserId(Integer.valueOf(user.getId()));
            live.setLiveName(user.getUserName());
            live.setType(2);
            live.setLiveNum(user.getUserNum());
            live.setParentUser(String.valueOf(userId));
            live.setRole(liveUser.getRole());
            jdLiveMapper.insert(live);
            JdAppUserRole userRole = new JdAppUserRole();
            userRole.setUserId(Integer.valueOf(user.getId()));
            if (liveUser.getRole() == 1) {
//                身份 1裁判/解说员 2赛场助理
                userRole.setRoleId(3);
            } else {
                userRole.setRoleId(4);
            }
            jdAppUserRoleMapper.insert(userRole);
        }
        return Success.success("添加成功", "");
    }

    @Override
    public JdAppUser getUserByIdOrPhone(String num) {
        JdAppUser user = jdAppUserMapper.selectOne(new QueryWrapper<JdAppUser>()
                .lambda()
                .eq(JdAppUser::getMobile, num)
                .last(" limit 1 ")
        );
        if (null == user) {
            user = jdAppUserMapper.selectOne(new QueryWrapper<JdAppUser>()
                    .lambda()
                    .eq(JdAppUser::getUserNum, num)
                    .last(" limit 1 ")
            );
        }
        return user;
    }

    /**
     * 是否主播
     *
     * @param userId 用户id
     * @return 0待审核 1是 2不是
     */
    @Override
    public Integer isAnchor(Integer userId) {
        JdLive live = lambdaQuery().eq(JdLive::getUserId, userId).eq(JdLive::getType, 1).last("limit 1").one();
        if (live == null) {
            return 2;
        }
        return 1;
    }

    /**
     * 删除主播角色
     *
     * @param liveId 主播id
     */
    @Override
    public void deleteLive(Integer liveId) {
        final JdLive live = jdLiveMapper.selectById(liveId);
        if (live == null) {
            return;
        }
        jdAppUserRoleMapper.delete(
                new LambdaQueryWrapper<JdAppUserRole>()
                        .eq(JdAppUserRole::getUserId, live.getUserId())
                        .eq(JdAppUserRole::getRoleId, 3)
        );
    }

    /**
     * 创建通用混流
     *
     * @param mixStreamParam 混流参数
     * @return RequestId     唯一请求 ID，每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
     */
    @Override
    public String createCommonMixStream(MixStreamParam mixStreamParam) {
        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        Credential cred = new Credential(LiveConfig.SECRET_ID, LiveConfig.SECRET_KEY);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("live.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        LiveClient client = new LiveClient(cred, "", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        CreateCommonMixStreamRequest req = new CreateCommonMixStreamRequest();
        req.setMixStreamSessionId(mixStreamParam.getMixStreamSessionId());
        //参数转数组
        final List<CommonMixInputParam> inputParams = JSON.parseArray(JSON.toJSONString(mixStreamParam.getInputStreamList()), CommonMixInputParam.class);
        req.setInputStreamList(inputParams.toArray(new CommonMixInputParam[0]));
        final CommonMixOutputParams outputParams = JSON.parseObject(JSON.toJSONString(mixStreamParam.getOutputParams()), CommonMixOutputParams.class);
        req.setOutputParams(outputParams);
//            先取消混流 再重新创建
        CancelCommonMixStreamRequest request = new CancelCommonMixStreamRequest();
        request.setMixStreamSessionId(mixStreamParam.getMixStreamSessionId());
        try {
            client.CancelCommonMixStream(request);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        try {
            // 返回的resp是一个CreateCommonMixStreamResponse的实例，与请求对象对应
            CreateCommonMixStreamResponse resp = client.CreateCommonMixStream(req);
            // 输出json格式的字符串回包
            System.out.println(CreateCommonMixStreamResponse.toJsonString(resp));
            return CreateCommonMixStreamResponse.toJsonString(resp);
        } catch (TencentCloudSDKException e) {
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }
}
